<?php
namespace app\dao;
/**
 * @desc 商品数量更新log
 * @author liaojianwen
 * @date 2016-12-30
 */

use app\dao\BaseDAO;
use app\enum\EnumOther;
use yii\db\Query;
use app\helpers\Utility;
use app\enum\EnumOriginType;

class ProductUpdateLogDAO extends BaseDAO
{
	/**
	 * @desc 构造函数
	 * @author liaojianwen
	 * @date 2016-12-30
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_table = 'product_update_log';
		$this->_pKey ='log_id';
	}
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return '{{%product_update_log}}';
	}
	
	
	/**
	 * @desc 获取商品更新log
	 * @author liaojianwen
	 * @date 2017-01-04
	 */
	public function getProductLog($cond, $filter, $pageInfo)
	{
		$limit = $pageInfo ['pageSize'];
		$offset = ($pageInfo ['page'] - 1) * $limit;
		$selects = "log_id,l.product_id,l.update_num,origin_type,origin_id,origin_line_id,flag,num_unit,remark,initial_num,l.create_time,
				product_name";
		
		
		// $conditions = "t.delete_flag = :flag";
		// $params  =[
		// 		':flag'=>EnumOther::NO_DELETE,
		// ];
		// if(isset($cond['vendor']) && !empty($cond['vendor'])){
		// 	$conditions .=" and t.vendor_id =:vid";
		// 	$params[':vid'] =$cond['vendor'];
			
		// }
		// if(isset($cond['warehouse']) && !empty($cond['warehouse'])){
		// 	$conditions .=" and t.warehouse_id =:wid";
		// 	$params[':wid'] = $cond['warehouse'];
		// }
		
		$query = new Query();
		$query->select($selects)
			->from("$this->_table l")
			->leftJoin("product p","p.product_id = l.product_id")
			->leftJoin("unit u","u.unit_id = l.num_unit")
			->orderBy ( ['l.create_time'=>SORT_ASC]);
		
		if(isset($cond['starTime']) && !empty($cond['starTime'])){
			$query->andwhere(['between','l.update_time',strtotime($cond['starTime']), strtotime($cond['endTime'])]);
		}
		
		if(isset($cond['pname']) && !empty($cond['pname'])){
			$query->andWhere(['like', 'p.product_name', $cond['pname']]);
		}
		if($filter){
			if($filter == '1'){
				//入库
				$query->andWhere(['=','l.flag',EnumOther::IN_FLAG]);
			} elseif($filter =='2'){
				//出库
				$query->andWhere(['=','l.flag',EnumOther::OUT_FLAG]);
			}
		}
		$result ['count'] = $query->count ();
		$result ['list'] = $query->offset ( $offset )->limit ( $limit )->all ();
		foreach ($result['list'] as &$item)
		{
			if($item['flag'] == 1){
				//入库
				$item['in_quantity'] = $item['update_num'];
				$item['out_quantity'] = 0;
				$item['minus'] = $item['update_num'];
			} else {
				//出库
				$item['out_quantity'] = $item['update_num'];
				$item['in_quantity'] = 0;
				$item['minus'] = $item['update_num'];
			}
			$item['type'] = Utility::getArrayValue(EnumOriginType::$origin_type, $item['origin_type']);
				
		}
		
		$result ['page'] = array (
				'page' => $pageInfo ['page'],
				'pageSize' => $pageInfo ['pageSize']
		);
		return $result;
	}
}